package insigne.kernel.sgbdinterface.basics;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.StringTokenizer;
public class DBOperator {

	/* ############################### Fields ############################### */	
	/** host to the connection */
	public String host = "localhost";
	/** The login for root */
	public String root = "root";
	/** the password for user root */
	public String mdp = "";
	/** @see Connection */
	protected Connection con;
	/**
	 * Class constructor : initialize the url, user, and password
	 */
	public DBOperator(){
		try {
			//Register the JDBC driver for MySQL.
			Class.forName("com.mysql.jdbc.Driver");
		}
		catch (Exception e) {
		return;
		}
	}
	
	/* open connection */
	public void openConnection(){
		//Define URL of database server
		String url = "jdbc:mysql://" + host + ":3306/";
		//Get a connection to the database for root.
		try {
			con = DriverManager.getConnection(url, root, mdp);
			con.createStatement().executeQuery("USE foly;");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * Parse the query and return a result set
	 * @param query
	 * @return
	 * @throws SQLException
	 */
	public ResultSet executeQuery(String query) throws SQLException{
		StringTokenizer st = new StringTokenizer(query);
		String mode = st.nextToken();
		if(mode.equalsIgnoreCase("SELECT")){
			return executeSelect(query);
		}else{
			if (mode.equalsIgnoreCase("INSERT") || mode.equalsIgnoreCase("UPDATE")) {
				executeUpdate(query);
			} 
			return null;
		}
	}
	/**
	 * Execute select
	 * @throws SQLException 
	 */
	public ResultSet executeSelect(String query) throws SQLException{
		System.out.println(query);
		return con.createStatement().executeQuery(query);
	}	
	/**
	 * Execute an update, insert, or delete
	 * @throws SQLException 
	 */
	public int executeUpdate(String query) throws SQLException{
		System.out.println(query);
		Statement stmt = con.createStatement();
		stmt.executeUpdate(query,Statement.RETURN_GENERATED_KEYS);
		int res = 0;
		ResultSet rs = stmt.getGeneratedKeys();
		while(rs.next()){
			res = rs.getInt(1);
		}
		return res;
	}
}